package org.apache.ocean.main.client;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.ocean.CElement;
import org.apache.ocean.main.http.HttpParameters;
import org.apache.ocean.main.http.HttpTimeout;
import org.apache.ocean.main.util.XMLUtil;
import org.apache.ocean.main.util.XMLUtil.XMLException;
import org.jdom.Element;

public class Client {
	
	public static Snapshot getSnapshotFiles(URL url, long lease, HttpTimeout httpTimeout) throws Exception {
		HttpParameters parameters = new HttpParameters("action", "getsnapshotfiles", "lease", lease);
		OceanXML response = OceanXML.request(url, parameters, httpTimeout);
		Snapshot snapshot = new Snapshot(response.getFirstInBody());
		return snapshot;
	}
	
	public static class Snapshot implements CElement {
		private long id;
		private List<Index> indices = new ArrayList<Index>();
		
		public Snapshot(Element root) {
			id = XMLUtil.getAttributeLong("id", root);
			for (Element indexElement : XMLUtil.getChildren("index", root)) {
				indices.add(new Index(indexElement));
			}
		}
		
		public static class Index implements CElement {
			private long id;
			private List<File> files = new ArrayList<File>();
			
			public Index(long id) {
				this.id = id;
			}
			
			public Index(Element root) {
				id = XMLUtil.getAttributeLong("id", root);
				for (Element fileElement : XMLUtil.getChildren("file", root)) {
					addFile(new File(fileElement));
				}
			}
			
			public void addFile(File file) {
				files.add(file);
			}
			
			public Element toElement() {
				Element root = new Element("index");
				root.setAttribute("id", Long.toString(id));
				for (File file : files) {
					root.addContent(file.toElement());
				}
				return root;
			}
			
			public static class File implements CElement {
				private String name;
				private long size;

				public File(String name, long size) {
					this.name = name;
					this.size = size;
				}

				public String getName() {
					return name;
				}

				public long getSize() {
					return size;
				}

				public File(Element root) {
					name = XMLUtil.getAttributeString("name", root);
					size = XMLUtil.getAttributeLong("size", root);
				}
				
				public Element toElement() {
					Element root = new Element("file");
					root.setAttribute("name", name);
					root.setAttribute("size", Long.toString(size));
					return root;
				}
			}
		}
		
		public Element toElement() {
			Element root = new Element("snapshot");
			root.setAttribute("id", Long.toString(id));
			for (Index index : indices) {
				root.addContent(index.toElement());
			}
			return root;
		}
	}
}
